<?php

/**
 * @property StudentUser $StudentUser Description
 * @property BankUser $BankUser Description
 * @property Transaction $Transaction Description
 * @property Config $Config Description
 * @property TransactionBankDetail $TransactionBankDetail Description
 */
class BankAdminController extends AppController
{
    # Controller Name to be used

    var $name = 'BankAdmin';


    # Models to be used
    var $uses = array(
        'BankUser', 'StudentUser', 'BankBranch', 'Transaction', 'Config', 'TransactionBankDetail', 'StudentNotification',
        'BankReportTracking', 'FeeType', 'BankReportTracking', 'BankReportLog', 'BankFailedLogin','BankCreditAuthorization',
        'BankReversalAuthorization','BankBatch','Bank','StudentWallet','AuthenticatedApp'
    );

    # set the layout to use
    var $layout = 'bank_layout';

    function __validateLoginStatus()
    {
        //debug($this->Session->read('loginData'));
        if ($this->params['action'] != 'login' && $this->params['action'] != 'logout') {
            if ($this->Session->check('loginData') == false) {
                $this->redirect(array('action' => 'login?ref=' . $this->params['action']));
            } else {
                $auth_user = $this->Session->read('loginData');

                //check if the user has not done multiple login
                $db_login_session = $this->getLoginSession($auth_user['id']);
                $login_session = $auth_user['login_session'];

                if ($db_login_session != $login_session) {
                    $this->Session->setFlash('Your session has expired!');
                    $this->redirect(array('action' => 'logout'));
                }

                //authorize the user, if the user is not authorized to view this page then redirect them to their session
                if ($auth_user['user_type'] != 'bank_user') {
                    if ($auth_user['user_type'] == 'staff_user') {
                        $this->redirect(array('controller' => 'Staff', 'action' => 'index'));
                    } elseif ($auth_user['user_type'] == 'student_user') {
                        $this->redirect(array('controller' => 'Student', 'action' => 'index'));
                    } else {
                        $this->Session->setFlash('Unauthorised Access');
                        $this->redirect(array('action' => 'logout'));
                    }
                } else { // if bank_user, determine level and redirect to appropriate home screen
                    $action = $this->params['action'];
                    $user_level = $auth_user['user_level'];
                    if ($user_level == 'Admin') {
                       /* $res = is_int(strpos($action, 'admin'));
                        if (!$res) {

                        }*/
                    }
                    else{
                        $this->redirect(array('action' => 'logout'));
                    }
                }
            }
        }
    }

    private function getUserBankDetails()
    {
        $auth_user = $this->Session->read('loginData');
        $data = $this->BankBranch->find('first', array(
            'conditions' => array('BankBranch.id' => $auth_user['bank_branch_id']),
            'contain'=>array('Bank'),
            'recursive' => 1
        ));
        $data['User']['id'] = $auth_user['id'];
        $data['User']['name'] = $auth_user['fname'].' '.$auth_user['lname'];
        //debug($data);
        return $data;
    }

    private function getLoginSession($user_id)
    {
        $data = $this->BankUser->find('first', array(
            'conditions' => array('id' => $user_id),
            'recursive' => -1
        ));
        return $data['BankUser']['login_session'];
    }

    function beforeFilter()
    {
        parent::beforeFilter();
        $this->__validateLoginStatus();
        $bank_info = $this->getUserBankDetails();
        $this->set(compact('bank_info'));
    }

    public function login()
    {
        $this->redirect(array('Controller' => 'Bank','action' => 'login'));
    }

    private function createLoginSession($data)
    {
        $login_session = $this->randomString(50);
        $data['login_session'] = $login_session;
        $this->BankUser->save(array(
            'id' => $data['id'],
            'login_session' => $login_session
        ));
        return $data;
    }

    # Controller actions
    /**
     * @name index
     * @param void
     * @return Array of data.
     * @access public
     */

    function index()
    {
        $this->redirect(array('action' => 'admin_users'));
    }


    function editprofile()
    {
        if ($this->request->is('post')) {
            $error = false;
            $auth_user = $this->Session->read('loginData');

            //Check if the student is trying to use the same pass as the date of birth , then reject
            /*if(trim($this->request->data['BankUser']['password']) == $auth_user['date_of_birth']){
                $error = true;
                $this->Session->setFlash("Password Error, You can't use your default password as a new password. ");
            }*/

            if ($this->request->data['BankUser']['password']) {
                //echo 'yes';
                $this->request->data['BankUser']['password'] = md5(trim($this->request->data['BankUser']['password']));
                /* if($auth_user['first_time_pass_changed'] == 'No'){
                     $this->request->data['BankUser']['first_time_pass_changed'] = 'Yes';
                 }*/
            } else {
                $auth_user = $this->Session->read('loginData');
                $this->request->data['BankUser']['password'] = $auth_user['password'];
            }
            /* if($this->request->data['StudentUser']['cellphone']){
                 $cell = $this->request->data['StudentUser']['cellphone'];
                 $this->request->data['StudentUser']['cellphone'] = preg_replace('/-/', '', $cell);
             }*/

            if ($error) {
                $this->Session->write('process_error', 'yes');
            } else {
                $result = $this->BankUser->save($this->request->data);

                if ($result) {
                    //write data to session
                    $user = $this->BankUser->getUserById($this->request->data['BankUser']['id']);
                    $this->Session->write('loginData', $user['BankUser']);
                    $this->Session->setFlash('Your profile info has been updated !');
                    $this->Session->write('process_error', 'no');
                    $msg = "Dear " . $auth_user['fname'] . " your account profile has been updated.";
                } else {
                    $this->Session->setFlash('Sorry, your profile info could not be updated');
                    $this->Session->write('process_error', 'yes');
                }
            }

            $this->redirect(array('action' => 'editprofile'));
        }
        $controller = $this;
        $this->set(compact('controller'));
    }


    function admin_api_settings()
    {
        $bank_info = $this->getUserBankDetails();

        if ($this->request->is('post')) {
            $error = false;
            $bank_id = $bank_info['Bank']['id'];
            $new_api_id = $this->request->data['AuthenticatedApp']['app_id'];
            $new_app_key_pass = $this->request->data['AuthenticatedApp']['app_key_pass'];
            $new_app_key_salt = $this->request->data['AuthenticatedApp']['app_key_salt'];
            $app_key_hash = md5($new_app_key_pass . $new_app_key_salt);
            $this->request->data['AuthenticatedApp']['app_key'] = $app_key_hash;
            $result = $this->AuthenticatedApp->save($this->request->data);
            if ($result) {
                //write data to session
               //Update Bank api_id field
                $save = array(
                    'id'=>$bank_id,
                    'app_id'=>$new_api_id,
                    'app_key'=>$new_app_key_pass
                );
                $this->Bank->save($save);
                $this->Session->setFlash('API Profile Updated !');
                $this->Session->write('process_error', 'no');
            }
            else {
                $this->Session->setFlash('API Profile Could Not Be Updated');
                $this->Session->write('process_error', 'yes');
            }

            $this->redirect(array('action' => 'admin_api_settings'));
        }

        $app_id = $bank_info['Bank']['app_id'];
        $app_key = $bank_info['Bank']['app_key'];
        $data_api = $this->AuthenticatedApp->get_auth($app_id);
        $data_api['app_key'] = $app_key;

        $controller = $this;
        $this->set(compact('controller','data_api'));
    }


    /***************************  BANK ADMIN SECTION *********************/

    function admin_users($type = 'get')
    {
        $auth_user = $this->Session->read('loginData');
        $bank_id = $auth_user['bank_id'];

        if ($this->request->is('ajax')) {
            $this->autoRender = false;
            $this->autoLayout = false;

            switch ($type) {
                case 'get' :
                    $_POST = $this->BankUser->sanitize($_POST);
                    /**  Get posted data */
                    $page = isset($_POST['page']) ? $_POST['page'] : 1;
                    /** The current page */
                    $sortname = isset($_POST['sortname']) ? $_POST['sortname'] : 'id';
                    /** Sort column */
                    $sortorder = isset($_POST['sortorder']) ? $_POST['sortorder'] : 'desc';
                    /** Sort order */
                    $qtype = isset($_POST['qtype']) ? $_POST['qtype'] : '';
                    /** Search column */
                    $search_query = isset($_POST['query']) ? $_POST['query'] : '';
                    /** Search string */
                    $rp = isset($_POST['rp']) ? $_POST['rp'] : 10;
                    $limit = $rp;
                    $start = ($page - 1) * $rp;

                    //get users id for this company only

                    $condition_array = array(
                        'BankUser.bank_id'=>$bank_id,
                        'BankUser.deleted' => 'n'
                    );

                    if (!empty($search_query)) {
                        if ($qtype == 'username') {
                            $condition_array = array(
                                'BankUser.username' => $search_query,
                                'BankUser.deleted' => 'n'
                            );
                        } else {
                            $condition_array = array(
                                "BankUser.$qtype LIKE" => $search_query . '%',
                                'BankUser.deleted' => 'n'
                            );
                        }
                    }
                    $contain = array('BankBranch');
                    $data_table = $this->BankUser->find('all', array('conditions' => $condition_array, 'contain' => $contain, 'order' => "BankUser.$sortname $sortorder", 'limit' => $start . ',' . $limit, 'recursive' => 1));
                    $data_table_count = $this->BankUser->find('count', array('conditions' => $condition_array, 'recursive' => -1));

                    $total_records = $data_table_count;

                    if ($data_table) {
                        $return_arr = array();
                        foreach ($data_table as $obj) {
                            $return_arr[] = array(
                                'id' => $obj['BankUser']['id'],
                                'cell' => array(
                                    $obj['BankUser']['id'],
                                    $obj['BankUser']['fname'],
                                    $obj['BankUser']['mname'],
                                    $obj['BankUser']['lname'],
                                    $obj['BankUser']['username'],
                                    $obj['BankUser']['user_level'],
                                    $obj['BankUser']['active'],
                                    $obj['BankBranch']['branch_name'],
                                ),
                                'property' => array(
                                    'bg_color' => $obj['BankUser']['bg_color']
                                )
                            );
                        }
                        return json_encode(array('success' => true, 'total' => $total_records, 'page' => $page, 'rows' => $return_arr));
                    } else {
                        return json_encode(array('success' => false, 'total' => $total_records, 'page' => $page, 'rows' => array()));
                    }
                    break;

                case 'save' :
                    $type = 'add';
                    if ($_POST['id'] == 0) {
                    }
                    else{
                        $type = 'edit';
                    }
                    /*$bank_info = $this->getUserBankDetails();
                    $bank_id = $bank_info['Bank']['id'];*/
                    $user = $this->Session->read('loginData');
                    $bank_user_id = $user['id'];
                    $bank_id = $auth_user['bank_id'];

                    $results_api = $this->Api->post('/bank/modify_user', array(
                        'type' => $type,
                        'bank_id' =>$bank_id,
                        'user_id'=>$_POST['id'],
                        'username' => $_POST['username'],
                        'fname' => $_POST['fname'],
                        'lname' => $_POST['lname'],
                        'mname' => $_POST['mname'],
                        'user_level' => $_POST['user_level'],
                        'active' => $_POST['active'],
                        'branch_id' => $_POST['bank_branch_id'],
                        'bank_user_id' => $bank_user_id
                    ));

                    $msg= $results_api['message'];
                    if ($results_api['response_code'] == 0) {
                        $api_data = $results_api['data'];
                        if (empty($api_data)) {
                            return json_encode(array('code' => 0, 'msg' => $msg));
                        } else { //If new pass back extra data if needed.
                            return json_encode(array('code' => 0, 'msg' => $msg, 'id' => $api_data['id']));
                        }
                    }
                    else {
                        return json_encode(array('code' => 1, 'msg' => $msg));
                    }

                    break;

                case 'reset_password':

                    $results_api = $this->Api->post('/bank/reset_password', array(
                        'user_id'=>$_POST['id'],
                        'password' => $_POST['password'],
                        'bank_user_id' => $auth_user['id']
                    ));

                    $msg= $results_api['message'];
                    if ($results_api['response_code'] == 0) {
                        return json_encode(array('code' => 0, 'msg' => $msg));
                    }
                    else {
                        return json_encode(array('code' => 1, 'msg' => $msg));
                    }

                    break;

                case 'delete':
                     $results_api = $this->Api->post('/bank/delete_users', array(
                         'user_ids'=>$_POST['ids'],
                         'bank_user_id' => $auth_user['id']
                     ));

                    $msg= $results_api['message'];
                    if ($results_api['response_code'] == 0) {
                        return json_encode(array('code' => 0, 'msg' => $msg));
                    }
                    else {
                        return json_encode(array('code' => 1, 'msg' => $msg));
                    }
                    break;
            }
        }

        $list = $this->BankBranch->find('all', array(
            'conditions'=>array('bank_id'=>$bank_id),
            'recursive' => -1
        ));
        $branch_list = array();
        foreach ($list as $value) {
            $branch_list[] = array('id' => $value['BankBranch']['id'], 'name' => $value['BankBranch']['branch_name']);
        }

        //$this->layout = 'bank_admin_layout';

        $this->set(compact('branch_list'));
    }


    function _validateUsername($username = null)
    {
        $data = $this->BankUser->find('first', array(
            'conditions' => array('BankUser.username' => $username),
            'recursive' => -1
        ));

        if ($data) {
            return true;
        } else {
            return false;
        }
    }


    function randomPassString($length)
    {
        return $this->randomString($length);
    }


    function admin_branches($type = 'get')
    {
        $auth_user = $this->Session->read('loginData');
        $bank_id = $auth_user['bank_id'];
        if ($this->request->is('ajax')) {
            $this->autoRender = false;
            $this->autoLayout = false;
            $auth_user = $this->Session->read('loginData');
            switch ($type) {
                case 'get' :
                    $_POST = $this->BankUser->sanitize($_POST);
                    /**  Get posted data */
                    $page = isset($_POST['page']) ? $_POST['page'] : 1;
                    /** The current page */
                    $sortname = isset($_POST['sortname']) ? $_POST['sortname'] : 'id';
                    /** Sort column */
                    $sortorder = isset($_POST['sortorder']) ? $_POST['sortorder'] : 'desc';
                    /** Sort order */
                    $qtype = isset($_POST['qtype']) ? $_POST['qtype'] : '';
                    /** Search column */
                    $search_query = isset($_POST['query']) ? $_POST['query'] : '';
                    /** Search string */
                    $rp = isset($_POST['rp']) ? $_POST['rp'] : 10;
                    $limit = $rp;
                    $start = ($page - 1) * $rp;

                    //get users id for this company only

                    $condition_array = array(
                        'BankBranch.bank_id'=>$bank_id,
                        'BankBranch.deleted' => 'n'
                    );

                    if (!empty($search_query)) {
                        if ($qtype == 'branch_code') {
                            $condition_array = array(
                                'BankBranch.branch_code' => $search_query,
                                'BankBranch.deleted' => 'n'
                            );
                        } else {
                            $condition_array = array(
                                "BankBranch.$qtype LIKE" => $search_query . '%',
                                'BankBranch.deleted' => 'n'
                            );
                        }
                    }
                    $data_table = $this->BankBranch->find('all', array('conditions' => $condition_array, 'order' => "BankBranch.$sortname $sortorder", 'limit' => $start . ',' . $limit, 'recursive' => 1));
                    $data_table_count = $this->BankBranch->find('count', array('conditions' => $condition_array, 'recursive' => -1));

                    $total_records = $data_table_count;

                    if ($data_table) {
                        $return_arr = array();
                        foreach ($data_table as $obj) {
                            $return_arr[] = array(
                                'id' => $obj['BankBranch']['id'],
                                'cell' => array(
                                    $obj['BankBranch']['id'],
                                    $obj['BankBranch']['branch_name'],
                                    $obj['BankBranch']['branch_code'],
                                    $obj['BankBranch']['branch_name_full'],
                                    $obj['BankBranch']['address'],
                                    $obj['BankBranch']['phone1'],
                                    $obj['BankBranch']['phone2']
                                )
                            );
                        }
                        return json_encode(array('success' => true, 'total' => $total_records, 'page' => $page, 'rows' => $return_arr));
                    } else {
                        return json_encode(array('success' => false, 'total' => $total_records, 'page' => $page, 'rows' => array()));
                    }
                    break;

                case 'save' :
                    if ($_POST['id'] == 0) {
                        $type = 'add';
                    } else {
                        $type = 'edit';
                    }
                    $bank_info = $this->getUserBankDetails();

                    $results_api = $this->Api->post('/bank/modify_branch', array(
                        'type'=>$type,
                        'bank_id' => $bank_info['Bank']['id'],
                        'branch_id' => $_POST['id'],
                        'branch_name' => $_POST['branch_name'],
                        'branch_code' => $_POST['branch_code'],
                        'branch_full_name' => $_POST['branch_name_full'],
                        'address' => $_POST['address'],
                        'phone1' => $_POST['phone1'],
                        'phone2' => $_POST['phone2'],
                        'bank_user_id' => $auth_user['id']
                    ));
                    $msg= $results_api['message'];
                    if ($results_api['response_code'] == 0) {
                        $api_data = $results_api['data'];
                        if (empty($api_data)) {
                            return json_encode(array('code' => 0, 'msg' => $msg));
                        } else { //If new pass back extra data if needed.
                            return json_encode(array('code' => 0, 'msg' => $msg, 'id' => $api_data['id']));
                        }
                    }
                    else {
                        return json_encode(array('code' => 1, 'msg' => $msg));
                    }

                    break;

                case 'delete':
                    $results_api = $this->Api->post('/bank/delete_branches', array(
                        'branch_ids'=>$_POST['ids'],
                        'bank_user_id' => $auth_user['id']
                    ));

                    $msg= $results_api['message'];
                    if ($results_api['response_code'] == 0) {
                        return json_encode(array('code' => 0, 'msg' => $msg));
                    }
                    else {
                        return json_encode(array('code' => 1, 'msg' => $msg));
                    }
                    break;
            }
        }

        $list = $this->BankBranch->find('all', array(
            'conditions'=>array('bank_id'=>$bank_id),
            'recursive' => -1
        ));
        $branch_list = array();
        foreach ($list as $value) {
            $branch_list[] = array('id' => $value['BankBranch']['id'], 'name' => $value['BankBranch']['branch_name']);
        }

        $this->set(compact('branch_list'));
    }





    /************************** END BANK ADMIN SECTION *******************/

}